package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kyh.service.sys.RoleMenuService;
import com.kyh.sys.entity.RoleMenu;
import com.kyh.sys.mapper.RoleMenuMapper;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("roleMenuService")
public class RoleMenuServiceImpl implements RoleMenuService {

	@Autowired
	private RoleMenuMapper roleMenuMapper;

	@Override
	@Transactional
	public R add(RoleMenu entity) throws Exception {
		
		Long roleId = entity.getRoleId();
		Long menuId = entity.getMenuId();
		// 验证是否存在
		RoleMenu roleMenuCheck = roleMenuMapper.getByUk(roleId, menuId);
		if (roleMenuCheck != null) {
			return R.error("已存在");
		}
		
		// 添加数据
		if (roleMenuMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	@Transactional
	public R edit(RoleMenu entity) throws Exception {
		
		// 更新数据
		if (roleMenuMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	public R deleteTrueByUk(Long roleId, Long menuId) throws Exception {
		
		// 验证是否存在
		RoleMenu roleMenuCheck = roleMenuMapper.getByUk(roleId, menuId);
		if (roleMenuCheck == null) {
			return R.error("不存在");
		}
		
		roleMenuMapper.deleteByUk(roleId, menuId);
		
		return R.ok();
	}

	@Override
	@Transactional
	public R deleteFalse(Long roleMenuId) throws Exception {
		
		if (roleMenuMapper.deleteFalse(roleMenuId) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	public BootstrapTableVoJA search(RoleMenu cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}
}
